package com.szl.yeb.controller;

import com.szl.yeb.common.R;
import com.szl.yeb.dto.LoginInfo;
import com.szl.yeb.entity.Admin;
import com.szl.yeb.service.AdminService;
import com.szl.yeb.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;

/**
 * @program: yeb
 * @description: 用户登录接口
 * @author: szl
 * @create: 2022-08-24 19:41
 **/
@RestController
@Api(tags = "用户登录接口(LoginController)", value = "LoginController")
public class LoginController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @PostMapping("/login")
    @ApiOperation("用户登录返回token")
    public R<Object> login(@RequestBody LoginInfo loginInfo, HttpServletRequest request) {
        return adminService.login(loginInfo, request);
    }

    @GetMapping("/admin/info")
    @ApiOperation("获取登录用户信息")
    public R<Object> getAdminInfo(Principal principal) {
        if (principal.getName() == null) {
            return R.error();
        }
        Admin admin = adminService.getAdminByUsername(principal.getName());
        admin.setRoles(roleService.getRolesByAdminId(admin.getId()));
        admin.setPassword(null);
        return R.obj(admin);
    }

    @PostMapping("/logout")
    @ApiOperation("注销登录")
    public R<Object> logout() {
        return R.okMsg(("注销成功"));
    }
}
